require "View/UITaskInfo/TimeBox/TimeBoxItem"

---@class TimeBoxPanel : UIComponentInterface
TimeBoxPanel = Class("TimeBoxPanel",UIComponentInterface)
local t = TimeBoxPanel
local priorityPutList = {4,1,5,2,6,3}
function t:OnCreate(obj)
    self.fguiObj = obj
    self.idList = TimeBoxHandler.CONST_BOX_ID_LIST
    self.boxMaxNum = self:GetChild("boxMaxNum")
    self.boxMaxNum2 = self:GetChild("boxMaxNum2")
    self.firstList = self:GetList("firstList")
    self.secondList = self:GetList("secondList")
    self.itemList = self:GetList("listBox")
    --self.unlockText = self:GetChild("unlockText")
    self.btnInfo = self:GetChild("btnInfo")
    self.btnQuicklyPut = self:GetChild("btnQuicklyPut")
    self.btnQuicklyReceive = self:GetChild("btnQuicklyReceive")
    self.ctrlSequence = self:GetController("ctrlSequence")
    self.ctrlBtnReceiveReady = self:GetController("status",self.btnQuicklyReceive)
    self:SetDynamicList(self.firstList,self.FirstItemRender,nil,true)
    self:SetDynamicList(self.secondList,self.SecondItemRender,nil,true)
    self:SetDynamicList(self.itemList,self.ItemBoxRender,nil,true)
    self:RegisterOnClick(self.btnQuicklyPut,self.ClickQuickPut)
    self:RegisterOnClick(self.btnQuicklyReceive,self.ClickQuickReceive)
    self:RegisterOnClick(self.btnInfo,self.ClickInfo)
    self.itemState = {0,0,0,0,0,0}
    self.poolMgr = ComponentPoolMgr.New(TimeBoxItem)

    self:RegisterEvent()
    TimeBoxHandler.ReqTimeBoxInfoUpdate()
end
function t:RegisterEvent()
    ListenEvent(Config.EventType.TimeBoxUpdate,self.TimeBoxUpdateMsg,self)
    ListenEvent(Config.EventType.Fresh_Bag,self.RefreshBox,self)

end
function t:UnRegisterEvent()
    CloseEvent(Config.EventType.TimeBoxUpdate,self.TimeBoxUpdateMsg,self)
    CloseEvent(Config.EventType.Fresh_Bag,self.RefreshBox,self)
    UIRedDots.removeViewEvent(PanelNames.UITaskInfo)

end
function t:RefreshBox()
    self.itemList.numItems = #self.idList
end
function t:Refresh()
    UIRedDots.addViewListen(PanelNames.UITaskInfo,self.fguiObj.name..self.btnQuicklyPut.name, self.btnQuicklyPut,Config.RedDotsType.TimeBoxAdd);
    UIRedDots.addViewListen(PanelNames.UITaskInfo,self.fguiObj.name..self.btnQuicklyReceive.name, self.btnQuicklyReceive,Config.RedDotsType.TaskTimeBox);
    self.firstList.numItems = TimeBoxHandler.MAX_COUNT
    self.secondList.numItems = TimeBoxHandler.MAX_COUNT
    self:RefreshBox()
    self.boxMaxNum.text = TimeBoxHandler.GetBoxCount(1).."/"..self:GetMaxBoxCount(1)
    self.boxMaxNum2.text = TimeBoxHandler.GetBoxCount(2).."/"..self:GetMaxBoxCount(2)

    local type,param =TimeBoxHandler.GetBoxLockLevel(2,1)
    if type == 0 then
        self.ctrlSequence.selectedIndex = 1
    else
        self.ctrlSequence.selectedIndex = 0
        --self.unlockText.text = param
    end
end

function t:GetMaxBoxCount(sequence)
    local max = TimeBoxHandler.MAX_COUNT
    local count = 0
    for j = 1,max do
        local type,param = TimeBoxHandler.GetBoxLockLevel(sequence,j)
        if type == 0 then
            count = count +1
        end
    end
    return count
end
function t:ItemBoxRender(index,go)
    local id = self.idList[index]
    local itemId = ItemManager.getItemIdByModelId(id)
    local ctrlAnim = go:GetController("ctrlState")
    local anim = go:GetChild("n56")
    local num =  logicMgr.ItemManager.getItemCountbyModelId(id)
    local item = CtrlManager.GetCtrl(PanelNames.Item)
    item.initData(go,{itemId = itemId, itemModelId = id,num = num})
    item.ShowBoxTime(go,id)
    item.DisableClick(go)
    local keyId = TimeBoxHandler.GetTimeBoxKey(id)
    local keyItemId = ItemManager.getItemIdByModelId(keyId)
    local keyNum = ItemManager.getItemCountbyModelId(keyId)
    local allNum = logicMgr.ItemManager.GetItemTimeBoxCount(id,true)
    if allNum >0 and keyNum > 0 then
        ctrlAnim.selectedIndex = 1
        Util.PlayAction(anim.wrapTarget,"idle1",true)
        anim.skinName = tostring(index)
    else
        ctrlAnim.selectedIndex = 0
    end
    go.onClick:Clear()
    go.onClick:Add(function()
        showUI(PanelNames.UIBagItemInfo,{itemId = keyItemId,itemModelId = keyId,num = keyNum}, 1,nil, true);
    end)
    UIRedDots.addViewListen(PanelNames.UITaskInfo,self.fguiObj.name.."_box"..index, go,Config.RedDotsType.TaskTimeBoxKeyEnough,keyId);
end
function t:FirstItemRender(index,go)
    ---@type TimeBoxItem
    local item = self.poolMgr:GetBindScript(go)
    local enum = Config.FuncOpenType.TimeBox1;
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UITaskInfo,Config.FuncOpenType["TimeBox"..index], "TimeBox"..index,go);

    item:Refresh(1,index,self.StateChangeCallback,self)
end
function t:SecondItemRender(index,go)
    ---@type TimeBoxItem
    local item = self.poolMgr:GetBindScript(go)
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UITaskInfo,Config.FuncOpenType["TimeBox"..(index+3)], "TimeBox"..index,go);
    item:Refresh(2,index,self.StateChangeCallback,self)
end
---@param item TimeBoxItem
function t:StateChangeCallback(item)
    local index = (item.sequence -1) * TimeBoxHandler.MAX_COUNT + item.index
    self.itemState[index] = item.state
    local hasReward = false
    local hasEmpty = false
    for k,v in pairs(self.itemState) do
        if v == TimeBoxItem.REWARD_STATE.reward then
            hasReward = true
        elseif v == TimeBoxItem.REWARD_STATE.empty then
            hasEmpty = true
        end
    end
    self.hasReward = hasReward
    self.hasEmpty = hasEmpty
    self.ctrlBtnReceiveReady.selectedIndex = self.hasReward and 1 or 0
end
function t:SetRewardShowId(id)
    self.rewardShowId = id
end
---@param evt FairyGUI.EventContext
function t:ClickStateBtn(evt)
    if not self.hasReward then
        return
    end
    TimeBoxHandler.ReqTimeBoxReward(1)  --一键领取
end
---一键领取
function t:ClickQuickReceive()
    if not self.hasReward then
        UISysTips.AddMsg(getLanguage("Sys_Friend_Gift_No_Gift_Get"))--无奖励
        return
    end
    local maxId = 0
    local maxQ = 0
    for k,v in pairs(self.itemState) do
        local sequence = math.floor((k-1)/TimeBoxHandler.MAX_COUNT) + 1
        local index = (k-1)%TimeBoxHandler.MAX_COUNT + 1
        if v == TimeBoxItem.REWARD_STATE.reward then
            local id = TimeBoxHandler.GetBoxId(sequence,index)
            if id > 0 then
                local q = dataTable.getDataTableByStringId("t_item",id,"f_Quality")
                if q > maxQ then
                    maxId = id
                    maxQ = q
                end
            end
        end
    end
    TimeBoxHandler.SetRewardShowId(maxId)
    TimeBoxHandler.ReqTimeBoxReward(1)
end
function t:ClickInfo()
    logicMgr.UIShowManager.ShowCommonTips("HelpTitle31","HelpDes31","FunctionStory2009")
end
---一键添加
function t:ClickQuickPut()
    if not self.hasEmpty then
        UISysTips.AddMsg(getLanguage("TimeBoxNoGridTip"))
        return
    end
    local list = logicMgr.ItemManager.getItemDatabyItemType(EnumConst.ItemTypeEnum.TimeBox)
    if #list == 0 then
        UISysTips.AddMsg(getLanguage("TimeBoxNoBoxTip"))
        return
    end
    local stateTb,ownCount = TimeBoxHandler.GetBoxRemainingState()
    if ownCount > 0 then
        local filterCount = 0
        table.sort(list,function(a,b) return a.quality > b.quality  end)
        for k,v in pairs(priorityPutList) do
            filterCount = filterCount + self:FilterSlot(v,stateTb,list)
        end
        if filterCount > 0 then
            for k,v in pairs(stateTb) do
                if v == 1 then
                    stateTb[k] = 0
                end
            end
            TimeBoxHandler.ReqTimeBoxAddBox(0,0,stateTb)
        end
    else
        UISysTips.AddMsg(getLanguage("TimeBoxNoGridTip"))
    end
end
function t:FilterSlot(index,stateTb,itemList)
    if stateTb[index] == 1 then--空
        if #itemList == 0 then return 0 end
        local item = itemList[1]
        if item.num == 0 then
            table.remove(itemList,1)
            return self:FilterSlot(index,stateTb,itemList)
        end
        stateTb[index] = item.itemId
        item.num = item.num - 1
        return 1
    end
    return 0
end
function t:OnDestroy()
    self.itemList = nil
    self.bind = nil
    self.poolMgr:OnDestroy()
    self.poolMgr = nil
    self:UnRegisterEvent()
    self.itemState = nil
end

function t:TimeBoxUpdateMsg()
    self:Refresh()
end